<?php

/**
 * 小班系统，根据不同条件获取练习列表
 * Created by PhpStorm.
 * User: devforma
 * Date: 16-5-20
 * Time: 下午6:20
 */

require __DIR__ . '/includes/VipUtils.class.php';
class GetFilteredExercise implements iController {

    public function output($queryArgs) {

        global $cmsdb, $uddb;

        //参数校验
        if (validateUser($queryArgs) !== 1 || !isset($queryArgs['status_id']) || !isset($queryArgs['category_id'])
            || !isset($queryArgs['type_id'])) {
            return genOutput(1000);
        }

        //过滤字段
        $userId     = intval($queryArgs['user_id']);        //用户
        $status     = intval($queryArgs['status_id']);      //状态
        $category   = intval($queryArgs['category_id']);    //科目
        $type       = intval($queryArgs['type_id']);        //类型

        //获取用户已购课程,字符串形式
        $courseStr = $this->getUserPurchasedCourses($userId);


        /**======================================================
         | 获取与用户产生关联的作业,指定用户的作业或已提交、完成的作业
         ------------------------------------------------------*/
        $sql = "SELECT upe.id, upe.exercise_id, pe.assign_type, upe.start_time, upe.end_time, upe.status 
                FROM userdata.`history_user_primary_exercise` AS upe INNER JOIN educms.`data_primary_exercise` AS pe 
                ON upe.user_id={$userId} AND upe.exercise_id=pe.id";
        $userExerciseData = (array)$cmsdb->getResults($sql);

        $userExercises = array();       //所有作业
        $noCourseExercises = array(); //指定用户的作业
        foreach ($userExerciseData as $e) {
            if ($e->assign_type == 1) {
                $noCourseExercises[] = $e->exercise_id;
            }

            $userExercises[$e->exercise_id] = $e;
        }

        //构造指定用户作业的IN查询字符串
        if (empty($noCourseExercises)) {
            $noCourseExerciseStr = '0';
        } else {
            $noCourseExerciseStr = implode(',', $noCourseExercises);
        }


        /**======================================================
         | 获取作业信息
         ------------------------------------------------------*/
        $sql = "SELECT * FROM `data_primary_exercise` WHERE 1";

        //类型过滤
        if ($type != -1) {
            $sql .= " AND `type_id`={$type}";
        } elseif ($category != -1) { //科目过滤
            $typeStr = $this->getCategoryTypeStr($category);
            $sql .= " AND `type_id` IN ({$typeStr})";
        }

        //指定课程课堂或指定用户过滤
        $sql .= " AND (`assign_type`=0 AND `course_id` IN ({$courseStr}) OR (`assign_type`=1 AND `id` IN ({$noCourseExerciseStr})))";
        
        //时间过滤
        $now = date('Y-m-d H:i:s');
        $sql .= " AND `start_time`<'{$now}' AND `status`=1";

        //查询结果
        $list = (array)$cmsdb->getResults($sql);


        /**======================================================
         | 按照作业状态分组
         ------------------------------------------------------*/
        $done           = array(); //已完成, status_id=1
        $undone         = array(); //未完成(没有做的作业), status_id=0
        $outdated       = array(); //过期, status_id=6
        $rejected       = array(); //被驳回, status_id=4
        $submitted      = array(); //已提交(需要教师批改的作业才有的状态), status_id=3
        $outdateDone    = array(); //过期完成, status_id=5

        $now = date('Y-m-d H:i:s');
        foreach ($list as $item) {

            //格式化数据
            $structured = array(
                'exercise_id'   => (int)$item->id,
                'exercise_type' => (int)$item->type_id,
                'teacher_name'  => self::getLectorName($item->creator),
                'name'          => $item->name,
                'course_name'   => self::getCourseName($item->course_id),
                'class_name'    => self::getClassName($item->class_id)
            );

            if (!isset($userExercises[$item->id])) {  //还未产生用户-作业关系, 状态有: 未完成、已过期

                //排序key
                $sortKey = self::genSortKey($item->end_time, $item->id);

                //以公共作业来设置作业时间
                $structured['start_time']   = $item->start_time;
                $structured['end_time']     = $item->end_time;

                if ($item->end_time > $now) { //未完成
                    $structured['status']      = 0;
                    $structured['status_text'] = VipUtils::getStatusText(0);

                    //防止相同结束时间的作业被覆盖
                    $undone[$sortKey]  = $structured;

                } else {  //已过期
                    $structured['status']      = 6;
                    $structured['status_text'] = VipUtils::getStatusText(6);

                    //防止相同结束时间的作业被覆盖
                    $outdated[$sortKey] = $structured;
                }
                continue;
            }

            //已产生用户-作业关系, 状态有: 已完成、被驳回、已提交、过期完成、未完成、已过期
            $userExercise = $userExercises[$item->id];
            $sortKey      = self::genSortKey($userExercise->end_time, $item->id);


            //以用户作业记录来设置时间、状态
            $structured['start_time']   = $userExercises[$item->id]->start_time;
            $structured['end_time']     = $userExercises[$item->id]->end_time;
            $structured['status']       = (int)$userExercises[$item->id]->status;
            $structured['status_text']  = VipUtils::getStatusText($structured['status']);

            switch($userExercise->status) {
                case 0: //未完成,指定到人
                    if ($userExercise->end_time > $now) { //未过期
                        $undone[$sortKey]  = $structured;
                    } else { //过期了
                        $structured['status']      = 6; //更新状态为过期
                        $structured['status_text'] = VipUtils::getStatusText(6);

                        $outdated[$sortKey] = $structured;

                        //更新状态为过期
                        $uddb->update('history_user_primary_exercise', array('status' => 6), array('id' => $userExercise->id));
                    }

                    break;

                case 6: //已过期
                    $outdated[$sortKey]    = $structured;
                    break;

                case 1: //已完成
                    $done[$sortKey]        = $structured;
                    break;

                case 3: //已提交
                    $submitted[$sortKey]   = $structured;
                    break;

                case 4: //已驳回
                    $rejected[$sortKey]    = $structured;
                    break;

                case 5: //过期完成
                    $outdateDone[$sortKey] = $structured;
                    break;

                default:
            }
        }


        /**======================================================
        | 按照作业状态过滤及排序
        ------------------------------------------------------*/
        $filteredExercises = array();

        if ($status == -1 || $status == 4) { //被驳回优先级最高
            ksort($rejected);
            $filteredExercises = array_merge($filteredExercises, array_values($rejected));
        }

        if ($status == -1 || $status == 0) { //未完成
            ksort($undone);
            $filteredExercises = array_merge($filteredExercises, array_values($undone));
        }

        if ($status == -1 || $status == 6) { //已过期
            ksort($outdated);
            $filteredExercises = array_merge($filteredExercises, array_values($outdated));
        }

        if ($status == -1 || $status == 3) { //已提交
            ksort($submitted);
            $filteredExercises = array_merge($filteredExercises, array_values($submitted));
        }

        if ($status == -1 || $status == 5) { //过期完成
            ksort($outdateDone);
            $filteredExercises = array_merge($filteredExercises, array_values($outdateDone));
        }

        if ($status == -1 || $status == 1) { //已完成
            ksort($done);
            $filteredExercises = array_merge($filteredExercises, array_values($done));
        }

        return genOutput(1, array('exercises' => $filteredExercises));
    }


    /**
     * 获取状态名称
     *
     * @param int $statusId 状态id
     * @return string
     */
    public static function getStatusName($statusId) {
        global $cmsdb;

        $cacheKey = 'vip:func:getStatusName';
        if (($status = cacheGet($cacheKey)) == null) {
            $status = array();

            $results = $cmsdb->getResults('SELECT * FROM `conf_primary_exercise_status` ORDER BY `id` ASC');
            foreach ($results as $item) {
                $status[$item->id] = $item->name;
            }
            cacheSet($cacheKey, $status, 48*60*60);
        }

        return $status[$statusId];
    }


    /**
     * 获取作业老师名
     *
     * @param int $lectorId 教师id
     * @return string
     */
    public static function getLectorName($lectorId) {
        global $cmsdb;

        if (empty($lectorId)) {
            return '';
        }

        $cacheKey = 'vip:func:getLectorName';
        if (($lectors = cacheGet($cacheKey)) == null || !isset($lectors[$lectorId])) {
            if (!$lectors) {
                $lectors = array();
            }

            $lectors[$lectorId] = (string)$cmsdb->getVar('SELECT `name` FROM `data_teacher` WHERE `id`=:tid', array(':tid' => $lectorId));
            cacheSet($cacheKey, $lectors, 24*60*60);
        }

        return $lectors[$lectorId];
    }

    /**
     * 获取作业课程名
     *
     * @param int $courseId 课程id
     * @return string
     */
    public static function getCourseName($courseId) {
        global $cmsdb;

        if (empty($courseId)) {
            return '';
        }

        $cacheKey = 'vip:func:getCourseName';
        if (($courses = cacheGet($cacheKey)) == null || !isset($courses[$courseId])) {
            if (!$courses) {
                $courses = array();
            }

            $courses[$courseId] = (string)$cmsdb->getVar('SELECT `course_name` FROM `data_live_course` WHERE `id`=:cid', array(':cid' => $courseId));
            cacheSet($cacheKey, $courses, 24*60*60);
        }

        return $courses[$courseId];
    }


    /**
     * 获取作业课堂名
     *
     * @param int $classId 课堂id
     * @return string
     */
    public static function getClassName($classId) {
        global $cmsdb;

        if (empty($classId)) {
            return '';
        }

        $cacheKey = 'vip:func:getClassName';
        if (($classes = cacheGet($cacheKey)) == null || !isset($classes[$classId])) {
            if (!$classes) {
                $classes = array();
            }

            $classes[$classId] = (string)$cmsdb->getVar('SELECT `class_name` FROM `data_live_class` WHERE `id`=:cid', array(':cid' => $classId));
            cacheSet($cacheKey, $classes, 24*60*60);
        }

        return $classes[$classId];
    }

    /**
     * 获取用户已购课程
     *
     * @param int $userId 用户id
     * @return bool|string
     */
    private function getUserPurchasedCourses($userId) {
        global $cmsdb;

        $sql = 'SELECT `product_id` FROM `relation_user_product` WHERE `user_id`=:uid AND `product_type`="zhiboke"';
        $courses = (array)$cmsdb->getCol($sql, array(':uid' => $userId));

        return empty($courses) ? '0' : implode(',', $courses);
    }

    /**
     * 根据科目获取作业类型
     *
     * @param int $categoryId 科目id
     * @return string
     */
    private function getCategoryTypeStr($categoryId) {
        global $cmsdb;

        $cacheKey = 'vip:func:getCategoryType:'.$categoryId;
        if (($types = cacheGet($cacheKey)) == null) {
            $types = (array)$cmsdb->getCol('SELECT `id` FROM `conf_primary_exercise_type` WHERE `note_category_id`=:cid', array(':cid' => $categoryId));

            cacheAdd($cacheKey, $types, 24*60*60);
        }

        return implode(',', $types);
    }

    /**
     * 创建排序key
     *
     * @param string $date 作业结束日期
     * @param int $id 作业id
     * @return string
     */
    private static function genSortKey($date, $id) {
        return $date . dechex($id);
    }
}